package com.atguigu.create.singleton.type6;

/**
 * 单例模式-双重检查.推荐
 */
public class SingletonTest6 {
    public static void main(String[] args) {
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1==instance2);
        System.out.println("instance1:"+instance1.hashCode());
        System.out.println("instance2:"+instance2.hashCode());
    }
}

class Singleton{
    // 1. 私有化构造器
    private Singleton() {
    }

    // 2. 创建一个private static对象
    // 此处加volatile主要是为了保证变量在多线程的可读性与顺序执行->涉及到juc偏底层的原理
    private static volatile Singleton singleton;

    // 3. getInstance(懒汉式-双重检查)
    public static Singleton getInstance(){
        if(singleton==null){
            synchronized (Singleton.class){
                if(singleton==null){
                    singleton=new Singleton();
                }
            }
        }
        return singleton;
    }

}
